<template>
    <div class="add-care-page">
        <!-- 患者信息摘要栏 -->
        <div class="patient-summary-container">
            <div class="patient-summary-title">
                {{ patient.bedCode }} {{ patient.name }} 护理记录单
            </div>
            <div class="patient-summary-info">
                <span>姓名：{{ patient.name }}</span>
                <span>年龄：{{ patient.age }}</span>
                <span>性别：{{ patient.sex === 1 ? '男' : patient.sex === 0 ? '女' : '' }}</span>
                <span>科室：{{ patient.officeCode }}</span>
                <span>床号：{{ patient.bedCode }}</span>
                <span>入院日期：{{ patient.inDate }}</span>
                <span>住院号：{{ patient.hospitalNo }}</span>
            </div>
            <div class="patient-summary-diagnosis">
                诊断：{{ patient.diagnosis }}
            </div>
        </div>
        <!-- 表单区域 -->
        <div class="form-area">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="60px" class="care-form">
                <el-row :gutter="24">
                    <el-col :span="4">
                        <el-form-item label="体温" prop="temperature">
                            <el-input 
                                v-model="ruleForm.temperature" 
                                placeholder="℃" 
                                class="custom-input"
                                :suffix-icon="'Temperature'"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="心率" prop="heartRate">
                            <el-input 
                                v-model="ruleForm.heartRate" 
                                placeholder="次/分" 
                                class="custom-input"
                                :suffix-icon="'Heart'"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="呼吸" prop="breathe">
                            <el-input 
                                v-model="ruleForm.breathe" 
                                placeholder="次/分" 
                                class="custom-input"
                                :suffix-icon="'WindPower'"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="血压" prop="bloodPressure">
                            <el-input
                                v-model="bloodPressureInput"
                                placeholder="如 120/80 mmHg"
                                class="custom-input"
                                :suffix-icon="'Monitor'"
                                @blur="onBloodPressureBlur"
                                @change="onBloodPressureBlur"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="血氧" prop="oximetry">
                            <el-input 
                                v-model="ruleForm.oximetry" 
                                placeholder="%" 
                                class="custom-input"
                                :suffix-icon="'Oxygen'"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="21">
                        <el-form-item label="护理措施及效果" prop="measures" label-width="120px">
                            <el-input 
                                v-model="ruleForm.measures" 
                                type="textarea" 
                                :rows="4"
                                placeholder="请输入护理措施及效果..."
                                class="custom-textarea"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="签名" prop="signUrl" label-width="120px">
                            <div class="signature-container">
                                <div class="signature-pad">
                                    <div class="signature-header">
                                        <span class="signature-title">请在此处签名</span>
                                        <el-button size="small" @click="clearSignature" class="clear-button" type="danger" plain>清除</el-button>
                                    </div>
                                    <canvas
                                        ref="signCanvas"
                                        width="300"
                                        height="120"
                                        class="signature-canvas"
                                        @mousedown="startDraw"
                                        @mousemove="draw"
                                        @mouseup="endDraw"
                                        @mouseleave="endDraw"
                                        @touchstart="startDraw"
                                        @touchmove="draw"
                                        @touchend="endDraw"
                                    ></canvas>
                                </div>
                                <div v-if="ruleForm.signUrl" class="signature-preview">
                                    <div class="preview-title">签名预览</div>
                                    <img :src="ruleForm.signUrl" alt="签名预览" />
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row justify="center">
                    <el-col :span="24" class="form-buttons">
                        <el-button type="primary" size="large" @click="submitForm(ruleFormRef)" class="submit-button">保存</el-button>
                        <el-button size="large" @click="router.push('/DailyCareChart')" class="cancel-button">取消</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>

<script setup lang="ts">
import http from '@/api/http';
import { onMounted, reactive, watch, ref, computed } from 'vue';
import { useRoute } from 'vue-router';

import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import router from '@/router';

const route = useRoute();

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "patientCode": route.query.patientCode,
  "breathe": null,
  "temperature": null,
  "rate": 82,
  "oximetry": null,
  "heartRate": null,
  "bloodPressure": '',
  "maxBP": '',
  "minBP": '',
  "measures": "",
  "signUrl": "",
  "date": "",
  "time": ""
})

const locationOptions = ['Home', 'Company', 'School']

// 血压验证函数
const validateBloodPressure = (rule: any, value: string, callback: any) => {
  if (!bloodPressureInput.value) {
    callback(new Error('请输入血压值'));
    return;
  }

  if (!bloodPressureInput.value.includes('/')) {
    callback(new Error('请按格式输入（如：120/80）'));
    return;
  }

  const [max, min] = bloodPressureInput.value.split('/');
  const systolic = parseInt(max);
  const diastolic = parseInt(min);

  if (isNaN(systolic) || isNaN(diastolic)) {
    callback(new Error('请输入有效的数字'));
    return;
  }

  if (systolic < 60 || systolic > 200) {
    callback(new Error('收缩压必须在60-200mmHg之间'));
    return;
  }

  if (diastolic < 40 || diastolic > 120) {
    callback(new Error('舒张压必须在40-120mmHg之间'));
    return;
  }

  if (systolic <= diastolic) {
    callback(new Error('收缩压必须大于舒张压'));
    return;
  }

  callback();
};

// 添加签名验证函数
const validateSignature = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请完成签名'));
    return;
  }
  // 检查是否是默认的空白画布
  const canvas = document.createElement('canvas');
  canvas.width = 300;
  canvas.height = 120;
  const defaultDataUrl = canvas.toDataURL('image/png');
  if (value === defaultDataUrl) {
    callback(new Error('请完成签名'));
    return;
  }
  callback();
};

const rules = reactive<FormRules>({
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  time: [
    { required: true, message: '请选择时间', trigger: 'change' }
  ],
  temperature: [
    { required: true, message: '请输入体温', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value === '') {
          callback();
        } else {
          const temp = parseFloat(value);
          if (isNaN(temp)) {
            callback(new Error('请输入有效的数字'));
          } else if (temp < 35 || temp > 42) {
            callback(new Error('体温必须在35-42℃之间'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ],
  heartRate: [
    { required: true, message: '请输入心率', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback();
        } else {
          const rate = parseInt(value);
          if (isNaN(rate)) {
            callback(new Error('请输入有效的数字'));
          } else if (rate < 40 || rate > 180) {
            callback(new Error('心率必须在40-180次/分钟之间'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ],
  breathe: [
    { required: true, message: '请输入呼吸频率', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback();
        } else {
          const rate = parseInt(value);
          if (isNaN(rate)) {
            callback(new Error('请输入有效的数字'));
          } else if (rate < 12 || rate > 40) {
            callback(new Error('呼吸频率必须在12-40次/分钟之间'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ],
  bloodPressure: [
    { required: true, message: '请输入血压', trigger: 'blur' },
    { validator: validateBloodPressure, trigger: 'blur' }
  ],
  oximetry: [
    { required: true, message: '请输入血氧饱和度', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback();
        } else {
          const spo2 = parseInt(value);
          if (isNaN(spo2)) {
            callback(new Error('请输入有效的数字'));
          } else if (spo2 < 70 || spo2 > 100) {
            callback(new Error('血氧饱和度必须在70-100%之间'));
          } else {
            callback();
          }
        }
      },
      trigger: 'blur'
    }
  ],
  measures: [
    { required: true, message: '请输入护理措施及效果', trigger: 'blur' },
    { min: 10, message: '护理措施描述不能少于10个字符', trigger: 'blur' }
  ],
  signUrl: [
    { required: true, message: '请完成签名', trigger: 'change' },
    { validator: validateSignature, trigger: 'change' }
  ]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  
  if (!formEl) return;
  
  // 先验证签名
  try {
    await formEl.validateField('signUrl');
  } catch (err) {
    ElMessage.warning('请先完成签名');
    return;
  }

  // 验证整个表单
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        // 如果有签名，先上传到七牛云
        if (ruleForm.signUrl) {
          // 将base64图片数据转换为Blob
          const base64Data = ruleForm.signUrl.split(',')[1];
          const blob = base64ToBlob(base64Data, 'image/png');
          
          // 获取七牛云上传token
          const tokenRes = await http.get('/api/PatientReCord/GetQiniuToken');
          console.log('tokenRes:', tokenRes); // 添加日志，查看返回数据结构
          
          if (!tokenRes.success) {
            ElMessage.error(tokenRes.message || '获取上传凭证失败');
            return;
          }

          const qiniuData = tokenRes.data;
          
          // 构建FormData
          const formData = new FormData();
          formData.append('file', blob, `signature_${Date.now()}.png`);
          formData.append('token', qiniuData.token);
          formData.append('key', `signatures/${Date.now()}.png`);

          // 上传到七牛云
          const uploadRes = await fetch('https://upload-z1.qiniup.com', {
            method: 'POST',
            body: formData
          });
          
          const uploadResult = await uploadRes.json();
          console.log('uploadResult:', uploadResult); // 添加日志，查看上传结果
          
          if (!uploadResult.key) {
            ElMessage.error('图片上传失败');
            return;
          }

          // 更新表单中的签名URL为七牛云地址
          ruleForm.signUrl = `${qiniuData.domain}/${uploadResult.key}`;
        } else {
          ElMessage.warning('请先完成签名');
          return;
        }

        // 保存表单数据
        const res = await http.post('/api/PatientReCord/CreatePatientReCord', ruleForm);
        console.log(res);
        ElMessage.success('保存成功');
        router.push('/nursing');
      } catch (err) {
        console.error(err);
        ElMessage.error('保存失败');
      }
    } else {
      console.log('error submit!', fields);
    }
  });
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

const patient = reactive({
    name: '',
    officeCode: '',
    bedCode: '',
    sex: null,
    age: '',
    inDate: '2019-04-18',
    hospitalNo: '0055463',
    diagnosis: ''
});

const backPatient = () => {
    http.get('/api/DoctorManage/GetPatientsByPatientCode?patientCode=' + route.query.patientCode)
        .then(res => {
            Object.assign(patient, res.data[0]);
        })
        .catch(err => {
            console.log(err);
        });
};

onMounted(() => {
    backPatient();
    clearSignature();
});

watch(
    () => route.query.patientCode,
    (newVal, oldVal) => {
        if (newVal && newVal !== oldVal) {
            backPatient();
        }
    }
);

const bloodPressureInput = ref('');

watch(
  () => ruleForm.bloodPressure,
  (newValue) => {
    bloodPressureInput.value = newValue;
  }
);

const onBloodPressureBlur = async () => {
  if (bloodPressureInput.value.includes('/')) {
    const [max, min] = bloodPressureInput.value.split('/');
    ruleForm.maxBP = max ? max.trim() : '';
    ruleForm.minBP = min ? min.trim() : '';
    ruleForm.bloodPressure = bloodPressureInput.value;
  } else {
    ruleForm.maxBP = bloodPressureInput.value;
    ruleForm.minBP = '';
    ruleForm.bloodPressure = bloodPressureInput.value;
  }
  
  // 手动触发表单验证
  if (ruleFormRef.value) {
    await ruleFormRef.value.validateField('bloodPressure');
  }
};

const signCanvas = ref<HTMLCanvasElement | null>(null);
let drawing = false;
let lastX = 0;
let lastY = 0;

function getPos(e: MouseEvent | TouchEvent) {
  let x = 0, y = 0;
  if ('touches' in e && e.touches.length) {
    const rect = signCanvas.value!.getBoundingClientRect();
    x = e.touches[0].clientX - rect.left;
    y = e.touches[0].clientY - rect.top;
  } else if ('clientX' in e) {
    const rect = signCanvas.value!.getBoundingClientRect();
    x = e.clientX - rect.left;
    y = e.clientY - rect.top;
  }
  return { x, y };
}

function startDraw(e: MouseEvent | TouchEvent) {
  drawing = true;
  const { x, y } = getPos(e);
  lastX = x;
  lastY = y;
}

function draw(e: MouseEvent | TouchEvent) {
  if (!drawing) return;
  e.preventDefault();
  const ctx = signCanvas.value!.getContext('2d')!;
  ctx.strokeStyle = '#333';
  ctx.lineWidth = 2;
  ctx.lineCap = 'round';
  ctx.lineJoin = 'round';
  const { x, y } = getPos(e);
  ctx.beginPath();
  ctx.moveTo(lastX, lastY);
  ctx.lineTo(x, y);
  ctx.stroke();
  lastX = x;
  lastY = y;
}

function endDraw() {
  drawing = false;
  saveSignature();
}

function clearSignature() {
  const ctx = signCanvas.value!.getContext('2d')!;
  ctx.clearRect(0, 0, signCanvas.value!.width, signCanvas.value!.height);
  ruleForm.signUrl = '';
  // 手动触发签名验证
  if (ruleFormRef.value) {
    ruleFormRef.value.validateField('signUrl');
  }
}

function saveSignature() {
  ruleForm.signUrl = signCanvas.value!.toDataURL('image/png');
  // 手动触发签名验证
  if (ruleFormRef.value) {
    ruleFormRef.value.validateField('signUrl');
  }
}

// Base64转Blob工具函数
function base64ToBlob(base64: string, mimeType: string) {
  const byteCharacters = atob(base64);
  const byteNumbers = new Array(byteCharacters.length);
  for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  const byteArray = new Uint8Array(byteNumbers);
  return new Blob([byteArray], { type: mimeType });
}
</script>

<style scoped>
.add-care-page {
    max-width: 1200px;
    margin: 20px auto;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 24px;
}

.patient-summary-container {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 24px;
    margin-bottom: 24px;
}

.patient-summary-title {
    text-align: center;
    font-size: 22px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #ebeef5;
}

.patient-summary-info {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    font-size: 15px;
    margin-bottom: 16px;
}

.patient-summary-info span {
    color: #606266;
    line-height: 1.6;
    padding: 8px 12px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.patient-summary-diagnosis {
    font-size: 15px;
    color: #606266;
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    border-left: 4px solid #409eff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.form-area {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
}

.care-form .el-form-item {
    margin-bottom: 24px;
}

.custom-input {
    width: 100%;
}

.custom-input :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    transition: all 0.3s;
}

.custom-input :deep(.el-input__wrapper:hover) {
    box-shadow: 0 0 0 1px #409eff inset;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 0 0 1px #409eff inset;
}

.custom-textarea :deep(.el-textarea__inner) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;
    transition: all 0.3s;
}

.custom-textarea :deep(.el-textarea__inner:hover) {
    box-shadow: 0 0 0 1px #409eff inset;
}

.custom-textarea :deep(.el-textarea__inner:focus) {
    box-shadow: 0 0 0 1px #409eff inset;
}

.signature-container {
    display: flex;
    gap: 24px;
    align-items: flex-start;
    margin-top: 16px;
}

.signature-pad {
    position: relative;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    width: 300px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    overflow: hidden;
}

.signature-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f8f9fa;
    border-bottom: 1px solid #ebeef5;
}

.signature-title {
    font-size: 14px;
    color: #606266;
    font-weight: 500;
}

.signature-canvas {
    background: #fff;
    cursor: crosshair;
    display: block;
    width: 100%;
    height: 120px;
}

.signature-preview {
    flex: 1;
    max-width: 300px;
    padding: 16px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    background-color: #fafafa;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.signature-preview .preview-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 12px;
    font-weight: 500;
}

.signature-preview img {
    max-width: 100%;
    max-height: 120px;
    display: block;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.form-buttons {
    text-align: center;
    margin-top: 32px;
}

.submit-button {
    min-width: 120px;
    margin-right: 16px;
}

.cancel-button {
    min-width: 120px;
}

@media screen and (max-width: 768px) {
    .add-care-page {
        margin: 10px;
        padding: 16px;
    }

    .patient-summary-info {
        grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    }

    .patient-summary-info span {
        padding: 6px 10px;
    }

    .signature-container {
        flex-direction: column;
    }

    .signature-pad,
    .signature-preview {
        width: 100%;
        max-width: none;
    }

    .form-buttons {
        display: flex;
        flex-direction: column;
        gap: 12px;
    }

    .submit-button,
    .cancel-button {
        width: 100%;
        margin-right: 0;
    }
}
</style>